import 'dart:io';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:musicapp/model/daily_songs.dart';
import 'package:musicapp/model/lyric.dart';
import 'package:musicapp/model/mv.dart';
import 'package:musicapp/model/play_list.dart';
import 'package:musicapp/model/song_comment.dart' hide User;
import 'package:musicapp/model/top_list.dart';
import 'package:path_provider/path_provider.dart';

import 'package:musicapp/route/navigate_service.dart';
import 'package:musicapp/route/routers.dart';
import 'package:musicapp/utils/utils.dart';
import 'package:musicapp/widgets/loading.dart';

import 'package:musicapp/model/user.dart';
import 'package:musicapp/model/recommend.dart';
import 'package:musicapp/model/banner.dart' as mBanner;
import 'package:musicapp/model/album.dart';

import '../application.dart';

class NetUtils {
  static Dio _dio;

  static void init() async {
    // 获取沙盒路径， 用于储存cookie
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    CookieJar cj = PersistCookieJar(dir: tempPath);
    // _dio = Dio(BaseOptions(baseUrl: 'http://192.168.3.17:3000'))
    _dio = Dio(BaseOptions(baseUrl: 'http://192.168.48.214:3000'))
      ..interceptors.add(CookieManager(cj))
      ..interceptors.add(LogInterceptor(responseBody: true, requestBody: true));
  }

  static Future<Response> _get(
    BuildContext context,
    String url, {
    Map<String, dynamic> params,
    bool isShowLoading = true,
  }) async {
    if (isShowLoading) Loading.showLoading(context);
    try {
      return await _dio.get(url, queryParameters: params);
    } catch (e) {
      if (e.response.statusCode >= 300 && e.response.statusCode < 400) {
        Future.delayed(Duration(milliseconds: 200), () {
          Application.getIt<NavigateService>().popAndPushNamed(Routes.login);
          Utils.showToast('登录失效，请重新登录');
        });
        return Future.error(Response(data: -1));
      } else {
        print(e.response is String);
        return Future.value(e.response);
      }
      // else {
      //   print(e.response is Map);
      //   return Future.error(0);
      // }
    } finally {
      Loading.hideLoading(context);
    }
  }

  /// 登录
  static Future<User> login(
      BuildContext context, String phone, String password) async {
    var response = await _get(context, '/login/cellphone', params: {
      'phone': phone,
      'password': password,
    });
    return User.fromJson(response.data);
  }

  static Future<Response> refreshLogin(BuildContext context) async {
    return await _get(context, '/login/refresh', isShowLoading: false);
  }

  /// 首页 Banner
  static Future<mBanner.Banner> getBannerData(BuildContext context) async {
    var response = await _get(context, '/banner', params: {'type': 1});
    return mBanner.Banner.fromJson(response.data);
  }

  /// 推荐歌单
  static Future<RecommendData> getRecommendData(BuildContext context) async {
    var response = await _get(context, '/recommend/resource');
    return RecommendData.fromJson(response.data);
  }

  /// 新碟上架
  static Future<AlbumData> getAlbumData(
    BuildContext context, {
    Map<String, dynamic> params = const {'offset': 1, 'limit': 10},
  }) async {
    var response = await _get(context, '/top/album', params: params);
    return AlbumData.fromJson(response.data);
  }

  /// MV 排行
  static Future<MVData> getTopMvData(
    BuildContext context, {
    Map<String, dynamic> params = const {'offset': 1, 'limit': 10},
  }) async {
    var response = await _get(context, '/top/mv', params: params);
    return MVData.fromJson(response.data);
  }

  /// 每日推荐歌曲
  static Future<DailySongsData> getDailySongsData(BuildContext context) async {
    var response = await _get(context, '/recommend/songs');
    return DailySongsData.fromJson(response.data);
  }

  /// 歌单详情
  static Future<PlayListData> getPlayListData(
    BuildContext context, {
    Map<String, dynamic> params,
  }) async {
    var response = await _get(context, '/playlist/detail', params: params);
    return PlayListData.fromJson(response.data);
  }

  /// 排行榜首页
  static Future<TopListData> getTopListData(BuildContext context) async {
    var response = await _get(context, '/toplist/detail');
    return TopListData.fromJson(response.data);
  }

  /// 获取评论列表
  static Future<SongCommentData> getSongCommentData(
    BuildContext context, {
    @required Map<String, dynamic> params,
  }) async {
    var response = await _get(context, '/comment/music',
        params: params, isShowLoading: false);
    return SongCommentData.fromJson(response.data);
  }

  /// 获取歌词
  static Future<LyricData> getLyricData(
    BuildContext context, {
    @required Map<String, dynamic> params,
  }) async {
    var response =
        await _get(context, '/lyric', params: params, isShowLoading: false);
    return LyricData.fromJson(response.data);
  }
}
